package com.taptech.doufu.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.DisplayMetrics;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BitmapUtil {
	public static Bitmap getCircleBitmap(Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}

		/* STEP 1. convert rectangle bitmap to circle bitmap */
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;

		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}
		TTLog.s(width + "---circleBitmap--" + height);
		Bitmap circleBitmap = Bitmap.createBitmap(width, height,
				Config.ARGB_8888);
		Canvas canvas = new Canvas(circleBitmap);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);

		return circleBitmap;
	}

	public static Bitmap getCircleBitmapWithRing(Bitmap bitmap, int ringWidth) {
		if (bitmap == null) {
			return null;
		}

		/* STEP 1. convert rectangle bitmap to circle bitmap */
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;

		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap circleBitmap = Bitmap.createBitmap(width, height,
				Config.ARGB_8888);
		Canvas canvas = new Canvas(circleBitmap);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);

		/* STEP 2. add ring to the circle */
		int newRoundPx = (int) (roundPx + ringWidth);

		Bitmap circleWidthRingBitmap = Bitmap.createBitmap(2 * newRoundPx,
				2 * newRoundPx, Config.ARGB_8888);

		Canvas canvas2 = new Canvas(circleWidthRingBitmap);

		// step 2.1 paint a new ring
		final int ringColor = 0xffffffff;

		Paint paint2 = new Paint();
		paint2.setAntiAlias(true);
		paint2.setStyle(Style.STROKE);
		paint2.setColor(ringColor);
		paint2.setStrokeWidth(ringWidth);
		canvas2.drawCircle(newRoundPx, newRoundPx, newRoundPx - 1 - ringWidth
				/ 2, paint2);

		// step 2.2 paint the circleBitmap into the canvas
		canvas2.drawBitmap(circleBitmap, ringWidth, ringWidth, new Paint());
		return circleWidthRingBitmap;
	}



	public static void saveSDcard(Bitmap b, String filePath) {
		File file = new File(filePath);
		FileOutputStream fos = null;
		try {
			file.createNewFile();
			fos = new FileOutputStream(filePath);
			if (null != fos) {
				b.compress(Bitmap.CompressFormat.PNG, 0, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 将图片缩放到指定大小
	 * 
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap scaleBitmap(Bitmap bitmap, float w, float h) {
		if (bitmap == null) {
			return null;
		}
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleW = w / (float) width;
		float scaleH = h / (float) height;
		matrix.postScale(scaleW, scaleH);
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		return bitmap;
	}

	private static final int TEMP_STORAGE_SIZE = 1024 * 100;
	/**
	 * 通过简单处理后获取res中的bitmap对象
	 * 
	 * @param paramResources
	 * @param res
	 * @param width
	 *            长度
	 * @param height
	 *            高度
	 * @return bitmap 对象
	 */
	public static Bitmap decodeSampledBitmapFromResource(
			Resources paramResources, int res, int width, int height) {
		InputStream localInputStream = paramResources.openRawResource(res);
		BitmapFactory.Options localOptions = new BitmapFactory.Options();
		localOptions.inTempStorage = new byte[TEMP_STORAGE_SIZE];
		localOptions.inPreferredConfig = Bitmap.Config.RGB_565;
		localOptions.inPurgeable = true;
		localOptions.inInputShareable = true;
		localOptions.inSampleSize = calculateInSampleSize(localOptions, width,
				height);
		localOptions.inJustDecodeBounds = false;
		return BitmapFactory.decodeStream(localInputStream, null, localOptions);
	}
	/**
	 * 根据屏幕计算缩放比率
	 * 
	 * @param paramOptions
	 * @param width
	 *            长度
	 * @param height
	 *            高度
	 * @return 缩放比率
	 */
	public static int calculateInSampleSize(BitmapFactory.Options paramOptions,
			int width, int height) {
		int i = paramOptions.outHeight;
		int j = paramOptions.outWidth;
		int k = 1;
		if ((i > width) || (j > width)) {
			int m = Math.round(i / height);
			int n = Math.round(j / width);
			if (m < n);
			for (k = m;; k = n) {
				float f1 = j * i;
				float f2 = 2 * (width * height);
				while (f1 / (k * k) > f2)
					k++;
			}
		}
		return k;
	}

	/**
	 * 图片压缩
	 * @param bitMap
	 * @param maxSize 图片允许最大空间 单位：KB
	 * @return
	 */
	public static Bitmap imageZoom(Bitmap bitMap,double maxSize) {

		//将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] b = baos.toByteArray();
		//将字节换成KB
		double mid = b.length/1024;
		//判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			//获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			//开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
		}
		return bitMap;
	}



	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
								   double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	public static Bitmap scaleImage(Bitmap image,int size) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 85, out);
		float zoom = (float)Math.sqrt(size * 1024 / (float)out.toByteArray().length);

		Matrix matrix = new Matrix();
		matrix.setScale(zoom, zoom);

		Bitmap result = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, true);

		out.reset();
		result.compress(Bitmap.CompressFormat.JPEG, 85, out);
		while(out.toByteArray().length > size * 1024){
			System.out.println("StoryPosterActivity============"+out.toByteArray().length);
			matrix.setScale(0.9f, 0.9f);
			result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
			out.reset();
			result.compress(Bitmap.CompressFormat.JPEG, 85, out);
		}
		return result;
	}

 
}
